<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="6">
        <el-card class="box-card">
          <el-input
            v-model="filterText"
            placeholder="输入关键字过滤"
            clearable
          />
          <el-tree
            ref="tree"
            class="filter-tree"
            :data="data"
            :props="defaultProps"
            highlight-current
            default-expand-all
            :filter-node-method="filterNode"
            @node-click="handleNodeClick"
          />
        </el-card>
      </el-col>
      <el-col :span="18">
        <el-card class="box-card">
          <el-form ref="queryForm" :model="queryForm" label-width="100px" :inline="true" border>
            <el-form-item label="搜索：" prop="userName">
              <el-input
                v-model="queryForm.userName"
                placeholder="请输入关键词"
                prefix-icon="el-icon-search"
              />
            </el-form-item>
            <el-form-item>
              <el-button
                v-if="btnPermission('user:query:list')"
                type="success"
                size="mini"
                icon="el-icon-search"
                plain
                @click="searchData"
              >查询
              </el-button>
              <el-button
                v-if="btnPermission('user:query:list')"
                type="warning"
                size="mini"
                icon="el-icon-refresh-left"
                plain
                @click="resetQueryFrom"
              >重置
              </el-button>
            </el-form-item>
          </el-form>
          <el-row style="margin-bottom: 5px;">
            <el-col>
              <el-button
                v-if="btnPermission('user:add:entity')"
                :disabled="addDisabled"
                icon="el-icon-circle-plus-outline"
                plain
                size="mini"
                type="primary"
                @click="add"
              >
                新增
              </el-button>
              <el-button
                v-if="btnPermission('user:edit:entity')"
                :disabled="editDisabled"
                icon="el-icon-edit"
                plain
                size="mini"
                type="success"
                @click="edit"
              >
                编辑
              </el-button>
              <el-button
                v-if="btnPermission('user:del:entities')"
                :disabled="delDisabled"
                icon="el-icon-circle-close"
                plain
                size="mini"
                type="danger"
                @click="del"
              >删除
              </el-button>
            </el-col>
          </el-row>
          <el-table
            v-loading="loading"
            :data="tableData"
            style="width: 100%"
            stripe
            row-key="id"
            border
            :header-cell-style="{textAlign: 'center'}"
            @selection-change="handleSelectionChange"
          >
            <el-table-column
              align="center"
              type="selection"
              width="65"
            />
            <el-table-column
              type="index"
              label="序号"
              width="60"
              :index="indexMethod"
              align="center"
            />
            <el-table-column
              prop="logonName"
              label="系统账号"
            />
            <el-table-column
              prop="displayName"
              label="用户姓名"
            />
            <el-table-column
              prop="order"
              label="排序"
              align="center"
              width="60"
            />
            <el-table-column
              prop="createTime"
              label="创建时间"
              width="160"
            >
              <template slot-scope="scope">
                <span>{{ $moment(scope.row.createTime).format('YYYY-MM-DD HH:mm:ss') }}</span>
              </template>
            </el-table-column>
            <el-table-column
              prop="isEnabled"
              label="是否启用"
              align="center"
              width="80"
              @change="change"
            >
              <template slot-scope="scope">
                <el-tag v-if="scope.row.isEnabled === 1" type="success">启用</el-tag>
                <el-tag v-else type="danger">禁用</el-tag>
              </template>
            </el-table-column>
            <el-table-column
              prop="remark"
              label="备注"
              width="160"
            />
          </el-table>
          <div class="pagination">
            <el-pagination
              :current-page="queryCondition.PageIndex"
              :page-sizes="[10,15, 20,40,60,80,100]"
              :page-size="queryCondition.PageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="queryCondition.TotalCount"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
          <el-dialog :title="title" :visible.sync="dialogFormVisible" class="demo-ruleForm">
            <el-card class="box-card">
              <el-form ref="form" :model="form" :rules="rules" label-width="80px" label-position="left">
                <el-row>
                  <el-col span="12">
                    <el-form-item label="登录账号" prop="LogonName">
                      <el-input
                        v-model="form.logonName"
                        prefix-icon="el-icon-search"
                        placeholder="请输入用户账户"
                        class="colWidth"
                        @blur="userCheck"
                      />
                    </el-form-item>
                  </el-col>
                  <el-col span="12">
                    <el-form-item label="用户姓名" prop="DisplayName">
                      <el-input
                        v-model="form.displayName"
                        prefix-icon="el-icon-search"
                        placeholder="请输入用户姓名"
                        class="colWidth"
                      />
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col span="12">
                    <el-form-item label="座机号" prop="Telephone">
                      <el-input
                        v-model="form.telephone"
                        prefix-icon="el-icon-search"
                        placeholder="请输入座机号"
                        class="colWidth"
                      />
                    </el-form-item>
                  </el-col>
                  <el-col span="12">
                    <el-form-item label="手机号" prop="MobilePhone">
                      <el-input
                        v-model="form.mobilePhone"
                        prefix-icon="el-icon-search"
                        placeholder="请输入手机号"
                        class="colWidth"
                      />
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col span="12">
                    <el-form-item label="电子邮件" prop="Email">
                      <el-input
                        v-model="form.email"
                        prefix-icon="el-icon-search"
                        placeholder="请输入电子邮件"
                        class="colWidth"
                      />
                    </el-form-item>
                  </el-col>
                  <el-col span="12">
                    <el-form-item label="序号" prop="Order">
                      <el-input-number
                        v-model="form.order"
                        :min="0"
                        placeholder="请输入序号"
                        label="请输入序号"
                        class="colWidth"
                      />
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col span="12">
                    <el-form-item label="是否启用" prop="IsEnabled">
                      <el-radio-group
                        v-model="form.isEnabled"
                        placeholder="请选择是否启用"
                        class="colWidth"
                      >
                        <el-radio :label="0">禁用</el-radio>
                        <el-radio :label="1">启用</el-radio>
                      </el-radio-group>
                    </el-form-item>
                  </el-col>
                  <el-col span="12">
                    <el-form-item label="备注" prop="Remark">
                      <el-input
                        v-model="form.remark"
                        prefix-icon="el-icon-search"
                        placeholder="请输入备注"
                        class="colWidth"
                      />
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-form>
            </el-card>
            <div slot="footer" class="dialog-footer">
              <el-button icon="el-icon-circle-check" plain size="mini" type="success" @click="submitForm">确 定
              </el-button>
<!--              <el-button icon="el-icon-refresh-left" plain size="mini" type="warning" @click="resetForm">重 置</el-button>-->
              <el-button icon="el-icon-close" plain size="mini" type="danger" @click="dialogFormVisible = false">取 消
              </el-button>
            </div>
          </el-dialog>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { getEntity, getList } from '@/api/base-api'
import BasePage from '@/components/BasePage/BasePage'
import { generateQueryItem } from '@/utils/query-item'
import { Guid } from '@/constants/guid'
import { DateTime } from '@/constants/date'
import { validateEMail, validateMobilephone, validateTelephone } from '@/utils/validate'

export default {
  name: 'UserManagement',
  extends: BasePage,
  data() {
    return {
      queryForm: {
        userName: null
      },
      filterText: '',
      data: null,
      defaultProps: {
        children: 'children',
        label: 'orgName'
      },
      currentNode: null,
      form: {
        id: null,
        orgId: null,
        orgName: null,
        logonName: null,
        displayName: null,
        password: null,
        telephone: null,
        mobilePhone: null,
        email: null,
        isSupperAdmin: null,
        order: null,
        remark: null,
        isEnabled: null,
        isDel: null,
        creator: null,
        createTime: null,
        modifier: null,
        modifyTime: null
      },
      rules: {
        logonName: [
          { required: true, message: '请输入用户账号', trigger: 'blur' },
          { min: 0, max: 128, message: '长度在 0 到 128 个字符', trigger: 'blur' }
        ],
        displayName: [
          { required: true, message: '请输入用户姓名', trigger: 'blur' },
          { min: 0, max: 128, message: '长度在 0 到 128 个字符', trigger: 'blur' }
        ],
        telephone: [
          { validator: validateTelephone, trigger: 'blur' }
        ],
        mobilePhone: [
          { validator: validateMobilephone, trigger: 'blur' }
        ],
        email: [
          { validator: validateEMail, trigger: 'blur' }
        ],
        isEnabled: [
          { required: true, message: '请选中是否启用', trigger: 'blur' }
        ]
      }
    }
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val)
    }
  },
  created() {
    // window.addEventListener('storage', this.afterQRScan)
    this.url.queryList = 'UserManagement/Post'
    this.url.queryEntity = 'UserManagement/GetById/'
    this.url.addEntity = 'UserManagement/Add'
    this.url.editEntity = 'UserManagement/Put'
    this.url.deleteEntity = 'UserManagement/Delete/'
    this.url.deleteEntities = 'UserManagement/DeleteRange/'
    this.queryCondition.Sort = 'Order ASC'
  },
  mounted() {
    this.getTreeNodes()
  },
  destroyed() {
    // window.removeEventListener('storage', this.afterQRScan)
  },
  methods: {
    getTreeNodes: function() {
      getList('OrganizationManagement/Post', {
        PageIndex: 0, PageSize: 0, Sort: 'CreateTime DESC', TotalCount: 0, QueryItems: []
      }).then(response => {
        this.data = response.list
      })
    },
    filterNode(value, data) {
      if (!value) return true
      return data.orgName.indexOf(value) !== -1
    },
    searchData: function() {
      this.addDisabled = false
      this.queryCondition.PageIndex = 0
      this.queryCondition.QueryItems = []
      if (this.currentNode != null) {
        this.queryCondition.QueryItems.push(generateQueryItem(
          'OrgId',
          this.DataType.Guid,
          this.QueryMethod.Equal,
          this.currentNode.id))
      }
      if (this.queryForm.userName) {
        this.queryCondition.QueryItems.push(
          generateQueryItem('LogonName', this.DataType.String, this.QueryMethod.Like, this.queryForm.userName)
        )
        this.queryCondition.QueryItems.push(
          generateQueryItem('DisplayName', this.DataType.String, this.QueryMethod.OrLike, this.queryForm.userName)
        )
      }
      this.initData()
    },
    resetQueryFrom: function() {
      this.$refs.queryForm.resetFields()
      this.queryCondition.QueryItems = []
      this.getTreeNodes()
      this.initData()
    },
    change: function() {
      if (this.form.isEnabled === 0) {
        this.disabled = true
      }
    },
    handleNodeClick(data) {
      this.currentNode = data
      this.searchData()
    },
    add: function() {
      if (!this.currentNode) {
        this.$message({ showClose: true, message: '请选择机构', type: 'error' })
        return
      }
      this.resetForm()
      this.title = '新增用户'
      this.form.id = Guid.Empty
      this.form.orgId = this.currentNode.id
      this.form.orgName = this.currentNode.orgName
      this.form.password = '***'
      this.form.isSupperAdmin = 0
      this.form.isEnabled = 1
      this.form.isDel = 0
      this.form.creator = Guid.Empty
      this.form.createTime = DateTime.Default
      this.form.modifier = Guid.Empty
      this.form.modifyTime = DateTime.Default
      this.dialogFormVisible = true
    },
    edit: function() {
      this.loading = true
      this.resetForm()
      this.getEntity(this.multipleSelection[0].id).then(response => {
        this.title = '编辑用户'
        Object.assign(this.form, response.object)
        this.form.orgId = this.multipleSelection[0].orgId
        this.form.orgName = this.multipleSelection[0].orgName
        this.dialogFormVisible = true
        this.loading = false
      })
    },
    del: function() {
      this.$confirm('确定要将数据删除吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        if (this.multipleSelection.length === 1) {
          this.deleteEntity(this.multipleSelection[0].id).then(response => {
            this.$message({ showClose: true, message: '删除成功', type: 'error' })
            this.editDisabled = true
            this.delDisabled = true
            this.getTreeNodes()
            this.initData()
          })
        } else {
          const ids = this.multipleSelection.map((item) => {
            return item.id
          })
          this.deleteEntities(ids.toString()).then(response => {
            this.$message({ showClose: true, message: '删除成功', type: 'error' })
            this.editDisabled = true
            this.delDisabled = true
            this.getTreeNodes()
            this.initData()
          })
        }
      })
    },
    submitForm() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          if (this.form.id === null || this.form.id === Guid.Empty) {
            this.addEntity(this.form).then(response => {
              this.$message({ showClose: true, message: '保存成功', type: 'success' })
              this.dialogFormVisible = false
              this.editDisabled = true
              this.delDisabled = true
              this.getTreeNodes()
              this.initData()
            })
          } else {
            this.editEntity(this.form).then(response => {
              this.$message({ showClose: true, message: '编辑成功', type: 'success' })
              this.dialogFormVisible = false
              this.editDisabled = true
              this.delDisabled = true
              this.getTreeNodes()
              this.initData()
            })
          }
        }
      })
    },
    userCheck: function() {
      const url = 'UserManagement/IsExistedLogonName/'
      getEntity(url, this.form.logonName).then(response => {
        if (response.object === true) {
          this.$message({ showClose: true, message: '登录名已存在', type: 'error' })
          this.form.logonName = null
        }
      })
    },
    resetForm() {
      this.form.id = null
      this.form.orgId = null
      this.form.orgName = null
      this.form.logonName = null
      this.form.displayName = null
      this.form.password = null
      this.form.telephone = null
      this.form.mobilePhone = null
      this.form.email = null
      this.form.isSupperAdmin = null
      this.form.order = null
      this.form.remark = null
      this.form.isEnabled = null
      this.form.isDel = null
      this.form.creator = null
      this.form.createTime = null
      this.form.modifier = null
      this.form.modifyTime = null

      this.$nextTick(() => {
        this.$refs.form.resetFields()
      })
    }
  }
}</script>

<style scoped>
.colWidth {
  width: 250px;
}
</style>
